/**
 * 
 */
package com.xbang.attendance.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;

import com.xbang.attendance.entity.order.PurchaseDetails;
import com.xbang.attendance.entity.order.PurchaseOrder;
import com.xbang.attendance.helper.importexcel.PurchaseImportHelper;
import com.xbang.attendance.service.MaintenanceStationService;
import com.xbang.attendance.service.ProductService;
import com.xbang.attendance.service.PurchaseOrderService;
import com.xbang.core.utils.ReflectionUtils;

/**
 * @author dev.zhang
 * 
 */
// @Service("purchaseAnalyzeService")
public class PurchaseAnalyzeServiceImpl extends AbstractAnalyzeService {

	private final static Log logger = LogFactory.getLog(PurchaseAnalyzeServiceImpl.class);
	// @Autowired
	private ProductService productService;
	// @Autowired
	private MaintenanceStationService mainternaceStationService;
	// @Autowired
	private PurchaseOrderService purchaseOrderService;

	// @Autowired
	// @Qualifier("purchaseImportMap")
	private Map<String, String> fieldMapping = new HashMap<String, String>();

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.xbang.attendance.service.AnalyzeService#analyse(java.io.File)
	 */
	public void analyse(File file) throws Exception {
		//
		POIFSFileSystem fs = null;
		HSSFWorkbook wb = null;

		fs = new POIFSFileSystem(new FileInputStream(file));
		wb = new HSSFWorkbook(fs);

		List<PurchaseImportHelper> list = new ArrayList<PurchaseImportHelper>();

		for (int i = 0; i < wb.getNumberOfSheets(); i++) {

			HSSFSheet sheet = wb.getSheetAt(i);
			setupExcelFieldMappings(sheet);

			for (Row row : sheet) {

				if (row.getRowNum() == 0) {
					continue;
				}

				if (getCellValue(row.getCell(0)) == null || getCellValue(row.getCell(0)).toString().trim().isEmpty()) {
					continue;
				}
				PurchaseImportHelper purchaseImportHelper = new PurchaseImportHelper();

				for (Iterator<Map.Entry<String, Integer>> excelFieldMappingIterator = excelFieldMapping.entrySet().iterator(); excelFieldMappingIterator
						.hasNext();) {
					Entry<String, Integer> excelFieldMappingEntry = excelFieldMappingIterator.next();
					Object object = getCellValue(row.getCell(excelFieldMappingEntry.getValue()));
					if (object != null && fieldMapping.containsKey(excelFieldMappingEntry.getKey())) {
						String propertyName = fieldMapping.get(excelFieldMappingEntry.getKey()).split(":")[0];
						String[] propertys = fieldMapping.get(excelFieldMappingEntry.getKey()).split(":");
						if (propertys.length > 2) {
							if (propertys[2].toLowerCase().equals("date")) {
								logger.info(">>>>>>>>>>>>>>>>>>> " + object);
								object = getDateCellValue(row.getCell(excelFieldMappingEntry.getValue()));
								ReflectionUtils.setFeildByApache(purchaseImportHelper, propertyName, object);
							} else {
								ReflectionUtils.setFeildByApache(purchaseImportHelper, propertyName, object);
							}
						} else
							ReflectionUtils.setFeildByApacheCheckString(purchaseImportHelper, propertyName, object);
					}
				}

				list.add(purchaseImportHelper);
			}
		}

		//System.out.println(list);

		Map<String, PurchaseImportHelper> purchaseMaps = null;
		if (!list.isEmpty()) {
			purchaseMaps = toRepeat(list);
			int order = purchaseOrderService.getMaxOrder();
			for (Map.Entry<String, PurchaseImportHelper> entry : purchaseMaps.entrySet()) {
				PurchaseImportHelper tmpPurchaseImportHelper = entry.getValue();
				/* 如果不存在PO单号时 */
				//if (!purchaseOrderService.isPurchaseExist(tmpPurchaseImportHelper.getPoCode())) {
					if(!checkASC(tmpPurchaseImportHelper.getAscCode().trim())){
						throw new Exception("维修站编码为："+tmpPurchaseImportHelper.getAscCode()+" 不存在！");
					}
				//	System.out.println(tmpPurchaseImportHelper.getAscCode());
					PurchaseOrder purchaseOrder = new PurchaseOrder();
					purchaseOrder.setMaintenanceStation(mainternaceStationService.getMaintenanceStationByNumber(tmpPurchaseImportHelper.getAscCode().trim()));
					purchaseOrder.setAzkonobelDate(new Date());
					if (tmpPurchaseImportHelper.getOrderDate() == null) {
						purchaseOrder.setOrderDate(new Date());
					} else {
						purchaseOrder.setOrderDate(tmpPurchaseImportHelper.getOrderDate());
					}
					purchaseOrder.setOrderNumber(tmpPurchaseImportHelper.getPoCode());

					Map<String, PurchaseDetails> purchaseDetailsMaps = new HashMap<String, PurchaseDetails>();

					for (PurchaseImportHelper purchaseImportHelp : tmpPurchaseImportHelper.getList()) {
						/* 已经存在记录 */
						if (purchaseDetailsMaps.containsKey(purchaseImportHelp.getProCode())) {
							PurchaseDetails purchaseDetails = purchaseDetailsMaps.get(purchaseImportHelp.getProCode());
							BigDecimal proBigDecimal = purchaseDetails.getBalanceNumber();
							proBigDecimal = BigDecimal.valueOf(purchaseImportHelp.getProCount()).add(proBigDecimal);
							purchaseDetails.setBalanceNumber(proBigDecimal);
							purchaseDetails.setProductNumber(proBigDecimal);
							purchaseDetails.setServiceAmount(BigDecimal.valueOf(purchaseImportHelp.getServiceAmount()));
							purchaseDetailsMaps.put(purchaseImportHelp.getProCode(), purchaseDetails);
						} else {
							PurchaseDetails details = new PurchaseDetails();
							
							details.setProduct(productService.getProductByCode(purchaseImportHelp.getProCode().trim()));
							details.setProductNumber(BigDecimal.valueOf(purchaseImportHelp.getProCount() == null ? 0 : purchaseImportHelp.getProCount()));
							details.setPurchaseOrder(purchaseOrder);
							details.setBalanceNumber(BigDecimal.valueOf(purchaseImportHelp.getProCount() == null ? 0 : purchaseImportHelp.getProCount()));
							details.setServiceAmount(BigDecimal.valueOf(purchaseImportHelp.getServiceAmount() == null ? 0 : purchaseImportHelp
									.getServiceAmount()));
							purchaseDetailsMaps.put(purchaseImportHelp.getProCode(), details);
							purchaseOrder.getPurchaseDetails().add(details);
						}

					}

					purchaseOrder.setCompositor(++order);

					Serializable id = purchaseOrderService.save(purchaseOrder);
					purchaseOrder.setId(Integer.valueOf(id.toString()));
					for (Iterator<PurchaseDetails> purchaseDetailsIterator = purchaseOrder.getPurchaseDetails().iterator(); purchaseDetailsIterator.hasNext();) {
						PurchaseDetails purchaseDetails = purchaseDetailsIterator.next();
						purchaseDetails.setPurchaseOrder(purchaseOrder);
						purchaseOrderService.save(purchaseDetails);
					}

					purchaseOrder = purchaseOrderService.getPurchaseOrderByKey((Integer) id);
					// convertDeliveryOrder
					purchaseOrderService.convertDeliveryOrder(purchaseOrder, purchaseOrder.getPurchaseDetails());// 更新时不能调用它。
					//

			//	}// 存在单号
			//	else {
					//throw new  Exception("不能导入已经存在的单号！");
			//		purchaseOrderService.updatePurchaseOrder(tmpPurchaseImportHelper);
			//	}

			}
		}
	}

	private Boolean checkASC(String ascCode) throws Exception {
		return mainternaceStationService.checkMaintenanceStation(ascCode);
	}

	private Boolean checkPro(String proCode) throws Exception {
		return productService.checkProduct(proCode);
	}

	private Map<String, PurchaseImportHelper> toRepeat(List<PurchaseImportHelper> list) {
		Map<String, PurchaseImportHelper> map = new HashMap<String, PurchaseImportHelper>();
		for (PurchaseImportHelper temp : list) {
			if (map.containsKey(temp.getPoCode())) {
				map.get(temp.getPoCode()).addTemp(temp);
			} else {
				temp.addTemp(temp);
				map.put(temp.getPoCode(), temp);
			}
		}
		return map;
	}

	/**
	 * @param purchaseOrderService
	 */
	public void setPurchaseOrderService(PurchaseOrderService purchaseOrderService) {
		this.purchaseOrderService = purchaseOrderService;
	}

	/**
	 * @param productService
	 */
	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	/**
	 * @param mainternaceStationService
	 */
	public void setMainternaceStationService(MaintenanceStationService mainternaceStationService) {
		this.mainternaceStationService = mainternaceStationService;
	}

	/**
	 * @return the fieldMapping
	 */
	public Map<String, String> getFieldMapping() {
		return fieldMapping;
	}

	/**
	 * @param fieldMapping
	 *            the fieldMapping to set
	 */
	public void setFieldMapping(Map<String, String> fieldMapping) {
		this.fieldMapping = fieldMapping;
	}

}
